package com.zhipu.android.helper;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.provider.Settings;

import com.zhipu.android.MainApplication;
import com.zhipu.android.enums.EnumNetworkType;

/**
 * @file        NetworkHelper.java
 * @function    当前网络信息操作相关工具类
 * @author      占小平
 * @date        2015-8-5
 */
public class NetworkHelper {

	/*
	* @function		获取当前网络连接类型
	* @return		当前网络枚举类型
	* */
	public static EnumNetworkType getNetworkType() {
		if (applicationContext == null){
			updateApplicationContext();
		}

		ConnectivityManager conMan = (ConnectivityManager) applicationContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		// mobile 3G Data NetworkHelper
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();

		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return EnumNetworkType.NetworkTypeMobile;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return EnumNetworkType.NetworkTypeWifi;
		applicationContext.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));

		return EnumNetworkType.NetworkTypeNone;
	}

	/*
	* @function		判断当前网络是否连接
	* */
	public static boolean hasNetwork() {
		if (applicationContext == null){
			updateApplicationContext();
		}

		ConnectivityManager connectivityManager = (ConnectivityManager) applicationContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		int tryNo = 0;
		boolean result = false;
		while (tryNo < 2) {
			NetworkInfo info = connectivityManager.getActiveNetworkInfo();
			if (info == null) {
				CommonHelper.waitInterval(1);
				tryNo++;
			} else {
				result = info.isConnected();
				if (result)
					break;
				else {
					CommonHelper.waitInterval(1);
					tryNo++;
				}
			}
		}
		return result;
	}

	private static Context applicationContext = null;

	private static void updateApplicationContext(){
		applicationContext = MainApplication.application();
	}
}
